package com.contacts.servlet;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.contacts.pojo.Contact;
import com.contacts.service.ContactService;

public class WritecontactServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			File file=new File("D://contact.txt");
			if(!file.exists()){
				file.createNewFile();
			}
			//获取所有通讯人
			ContactService contactService=new ContactService();
			try {
				List<Contact> list = contactService.findAllContact();
				BufferedWriter writer=new BufferedWriter(new FileWriter(file));
				StringBuffer buffer =new StringBuffer();
				for(Contact contact:list){
					buffer.append("\t名字："+contact.getName()+"\t备注："+contact.getRem()+"\t电话："+contact.getPhone()+"\t住址："+contact.getAddr()+"\r\n");
				}
				writer.write(buffer.toString());
				request.setAttribute("msg", "导出成功");
				request.getRequestDispatcher("/findall").forward(request, response);
				writer.close();
				return ;
			} catch (Exception e) {
				request.setAttribute("msg", "导出失败");
				request.getRequestDispatcher("/findall").forward(request, response);
				e.printStackTrace();
			}
			
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}
